﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading.Tasks;
using System.Threading;
namespace BCL.Tool.Windows.Forms
{
    public partial class FormProgress : Form
    {
        static FormProgress fp;
        static Thread thread;
        static bool run=true;
        public static void Progress(int value, int max, string Title)
        {
            if (fp == null)
            {
                thread = new System.Threading.Thread(() =>
                {
                    fp = new FormProgress();
                    fp.Show();
                    while (run)
                        Application.DoEvents();
                });
                thread.Start();
            }
            while (fp == null || !fp.Created) ;

            if (value > max)
            {
                try
                {
                    fp.Invoke(new Action(() =>
                    {
                        fp.Close();
                        fp = null;
                    }));
                    run = false;
                    thread = null;
                }
                catch (Exception)
                {
                }
                return;
            }
            fp.Invoke(new Action(() =>
            {
                fp.Show();
                fp.label1.Text = Title + "...";
                fp.label2.Text = (((double)value / (double)max) * 100) + "%";
                fp.progressBar1.Maximum = max;
                fp.progressBar1.Value = value;
            }));
        }
        public FormProgress()
        {
            InitializeComponent();
        }
        public void SetProgress(int value, int max, string Title)
        {
            this.Invoke(new Action(() =>
            {
                if (value > max)
                {
                    this.Visible = false;
                    return;
                }
                this.Show();
                label1.Text = Title;
                this.progressBar1.Maximum = max;
                this.progressBar1.Value = value;
            }));
        }

        public static void CloseProgress()
        {
            if (fp != null && !fp.IsDisposed)
            {
                fp.Invoke(new Action(() =>
                {
                    fp.Close();
                    fp = null;
                }));
                run = false;
                thread = null;
            }
        }


        protected override void WndProc(ref Message m)
        {
            if (m.Msg == 0x0201)  //鼠标左键按下去的消息
            {
                m.Msg = 0x00A1;   //更改消息为非客户区按下鼠标
                m.LParam = IntPtr.Zero;  //默认值
                m.WParam = new IntPtr(2);  //鼠标放在标题栏内
            }
            base.WndProc(ref m);
        }
    }
}
